package com.example.webapp.controler;

import com.example.webapp.bean.Exam;
import com.example.webapp.bean.QuestionBank;
import com.example.webapp.bean.StudentExam;
import com.example.webapp.bean.User;
import com.example.webapp.service.ExamService;
import com.example.webapp.service.QuestionService;
import com.example.webapp.service.StudentExamService;
import com.example.webapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
public class AnswerControler {
    @Autowired
    private StudentExamService studentExamService;
    @Autowired
    private ExamService examService;
    @Autowired
    private UserService userService;
    @Autowired
    private QuestionService questionService;

    @CrossOrigin
    @PostMapping("/answer")
    @ResponseBody
    public String answer(@RequestBody Map map){
        String UidStr=(String)map.get("uid");
        Integer Uid=Integer.parseInt(UidStr);
        String ExamStr=(String)map.get("examid");
        Integer Examid=Integer.parseInt(ExamStr);
        List<LinkedHashMap> Answers=(List<LinkedHashMap>) map.get("answers");

        Exam nowExam=examService.getExamById(Examid);
        if(nowExam==null){
            return "no exam";
        }
        Optional<User> nowUser=userService.selectUserid(Uid);
        User ExamUser;
        if (!nowUser.isPresent()) {
            return "no user";
        } else {
            ExamUser=nowUser.get();
        }

        StudentExam AnswerLog;
        System.out.println(Answers.size());
        for(int i=0;i<Answers.size();i++){
            AnswerLog=new StudentExam();
            AnswerLog.setStudent(ExamUser);
            AnswerLog.setExam(nowExam);
            QuestionBank nowQuestion=questionService.getQuestionById(Integer.valueOf((String) Answers.get(i).get("id")));
            AnswerLog.setQuestion(nowQuestion);
            AnswerLog.setStudent_answer((String) Answers.get(i).get("answer"));
            if(((String) Answers.get(i).get("answer")).equals(nowQuestion.getQuestion_answer())){
                AnswerLog.setScore_get(5);
            }
            else{
                AnswerLog.setScore_get(0);
            }
            studentExamService.createStudentExam(AnswerLog);
        }

        return "success";
    }
}
